let app = getApp()
const util = require('../../util/util.js')
Page({
  data: {
    loading: 1,
    locationContent: "请在系统设置-应用权限管理中开启允许微信使用地理位置的开关",
    itemIndex:0,
    detailIndex:0,
    checkItemList:[],
    filesData:[],
    imgUrlData:[]
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    let that = this;
    //此处删除了定位
    // console.log(options)
    this.setData({
      checkClass: options.className,
      checkAddress: options.address,
      categoryId: options.categoryId,
      categoryName:options.categoryName
    })
    dd.httpRequest({
      url: app.baseUrl + '/DingDingSystem2/getInspectOneItemDeal',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: JSON.stringify({
        schoolId: app.globalData.departmentId,
        categoryId: options.categoryId,
        inspectPlanId: options.inspectPlanId,
      }),
      dataType: 'json',
      success: res => {
        console.log(res)
        let nowDate = new Date()
        for (let i = 0; i < res.data[0].contentList.length; i++) {
          res.data[0].contentList[i].inspectPlanId = options.inspectPlanId
          res.data[0].contentList[i].video = ""
          res.data[0].contentList[i].videoSrc = ""
        }
        this.setData({
          showAll: 0,
          connectTime: util.formatTime(nowDate),
          checkItemList: res.data
        })
      },
      fail: res => {
        dd.showToast({
          content: '网络异常！',
          type: 'fail'
        })
      },
      complete: () => {
        this.setData({
          loading: 0
        })
      }
    })
  },


  switchChange(e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    console.log("itemIndex:" + itemIndex + "detailIndex:" + detailIndex)
    let checkItemList = this.data.checkItemList
    if (e.detail.value == false) {
      checkItemList[itemIndex].contentList[detailIndex].status = 0
      checkItemList[itemIndex].contentList[detailIndex].contentLength = 0
      checkItemList[itemIndex].contentList[detailIndex].dealFiles = []
      checkItemList[itemIndex].contentList[detailIndex].imageUrl = []
      checkItemList[itemIndex].contentList[detailIndex].hide = false
      checkItemList[itemIndex].contentList[detailIndex].imageNum = 0
      checkItemList[itemIndex].contentList[detailIndex].recordContent = ""
      checkItemList[itemIndex].contentList[detailIndex].video = ""
      checkItemList[itemIndex].contentList[detailIndex].videoSrc = ""
    } else {
      checkItemList[itemIndex].contentList[detailIndex].status = 1
      checkItemList[itemIndex].contentList[detailIndex].recordContent = ""
      checkItemList[itemIndex].contentList[detailIndex].video = ""
      checkItemList[itemIndex].contentList[detailIndex].videoSrc = ""
    }
    this.setData({
      checkItemList: checkItemList,
    })
  },

  onShow:function(e){
    var that = this;
    let checkItemList = that.data.checkItemList
    if(checkItemList.length != 0){
      that.setData({
        checkItemList: checkItemList
      })
    }
  },

  //自定义相机组件
  toCamera:function(e){
    let commit
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    if (this.data.checkItemList[itemIndex].contentList[detailIndex].recordContent == null ||
        this.data.checkItemList[itemIndex].contentList[detailIndex].recordContent == undefined || this.data.checkItemList[itemIndex].contentList[detailIndex].recordContent == "") {
        commit = 0
    }
    if(commit == 0){
      dd.showToast({
        content: '请输入现场问题描述',
        type: "fail"
      })
    }else{
      dd.navigateTo({
        url: '/subpages/pages/cameraIdentified/cameraIdentified?recordContent='+
        this.data.checkItemList[itemIndex].contentList[detailIndex].recordContent+'&checkItemList='+JSON.stringify(this.data.checkItemList)+
        '&itemIndex='+itemIndex+'&detailIndex='+detailIndex+'&type=2'+'&address='+this.data.checkAddress
      })
    }
  },


  chooseImage: function (e) {
    var that = this;
    dd.chooseImage({
      count: 3,
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        dd.showLoading({
          content: "图片上传中...",
        })
        console.log("11", res)
        let tempImg = res.filePaths
        for (let i = 0; i < tempImg.length; i++) {
          dd.uploadFile({
            url: app.baseUrl + '/DingDingSystem/fileUpload',
            filePath: res.filePaths[i],
            fileName: 'file',
            fileType: 'image',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              if (res.data == "fail") {
                dd.showToast({
                  content: "图片上传失败",
                  type: "fail"
                })
              } else {
                dd.showToast({
                  content: "上传成功",
                  type: "success"
                })
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
                let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
                let checkItemList = that.data.checkItemList
                checkItemList[itemIndex].contentList[detailIndex].dealFiles.push(tempImg[i])
                checkItemList[itemIndex].contentList[detailIndex].imageUrl.push(res.data)
                checkItemList[itemIndex].contentList[detailIndex].imageNum++
                that.setData({
                  checkItemList: checkItemList
                })
                if (that.data.checkItemList[itemIndex].contentList[detailIndex].dealFiles.length == 3) {
                  checkItemList[itemIndex].contentList[detailIndex].hide = true
                  that.setData({
                    checkItemList: checkItemList
                  })
                }
              }
              dd.hideLoading()
            },
            fail: res => {
              dd.hideLoading()
              dd.showToast({
                content: "图片上传失败",
                type: "fail"
              })
            }
          })
        }

      }
    })
  },


  previewImageDeal: function (e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    let current = e.currentTarget.id.split('-')[2]
    let contentList = this.data.checkItemList[itemIndex].contentList[detailIndex]
    dd.previewImage({
      current: current, // 当前显示图片的http链接
      urls: contentList.dealFiles // 需要预览的图片http链接列表
    })
  },

  deleteImage: function (e) {
    let that = this
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    let imgIndex = parseInt(e.currentTarget.id.split('-')[2])
    let contentList = this.data.checkItemList[itemIndex].contentList[detailIndex]
    let target = contentList.imageUrl[imgIndex]
    let dealFiles = contentList.dealFiles[imgIndex]
    let dealFilesStr = "checkItemList[" + itemIndex + "].contentList[" + detailIndex + "].dealFiles"
    let imageUrlStr = "checkItemList[" + itemIndex + "].contentList[" + detailIndex + "].imageUrl"
    let imageNumStr = "checkItemList[" + itemIndex + "].contentList[" + detailIndex + "].imageNum"
    let hideStr = "checkItemList[" + itemIndex + "].contentList[" + detailIndex + "].hide"
    let temp = []
    let tempUrl = []
    let dealFilesLength = contentList.dealFiles.length
    for (let i = 0; i < dealFilesLength; i++) {
      if (i != imgIndex) {
        temp.push(contentList.dealFiles[i])
        tempUrl.push(contentList.imageUrl[i])
      }
    }

    dd.showActionSheet({
      items: ['删除这张照片'],
      cancelButtonText: '取消',
      success: res => {
        if (res.index != -1) {
          that.setData({
            [dealFilesStr]: temp,
            [imageUrlStr]: tempUrl
          })
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/deleteFile',
            method: 'POST',
            headers: {
              "Content-Type": "application/json"
            },
            data: JSON.stringify({
              filename: target.split("image/")[1]
            }),
            dataType: 'text',
            success: res => {
              let imageNum = contentList.imageNum - 1
              that.setData({
                [imageNumStr]: imageNum
              })
              if (dealFilesLength == 3) {
                that.setData({
                  [hideStr]: false
                })
              }
            }
          })
        }
      }
    })
  },


  inputContent: function (e) {
    e.detail.value = app.trim(e.detail.value)
    let itemIndex = parseInt(e.target.id.split('-')[0]),
      detailIndex = parseInt(e.target.id.split('-')[1]),
      checkItemList = this.data.checkItemList
    checkItemList[itemIndex].contentList[detailIndex].contentLength = parseInt(e.detail.value.length)
    checkItemList[itemIndex].contentList[detailIndex].recordContent = e.detail.value
    this.setData({
      checkItemList: checkItemList
    })
  },

  submit: util.throttle(function(e) {
    let list = this.data.checkItemList[0].contentList
    console.log(list)
    let that = this
    let commit
    let count = 0
    let photoOrVideo
    let unusualList = []
    for (let i = 0; i < list.length; i++) {
      if (list[i].status == 0) {
        if (list[i].recordContent == null || list[i].recordContent == undefined || list[i].recordContent == "") {
          commit = 0
        }
        if(list[i].imageUrl.length == 0 && list[i].video == "") {
          photoOrVideo = 0
        }
        unusualList.push(list[i])
      } else if (list[i].status == 1) {
        count++
      }
    }
    if (commit == 0) {
      dd.showToast({
        content: '请输入处理记录',
        type: "fail"
      })
    } else if(photoOrVideo == 0) {
      dd.showToast({
        content: '请附上照片或视频',
        type: "fail"
      })
    } else if (count == list.length) {
      // console.log("全部通过")
      dd.confirm({
        title: "温馨提示",
        content: "当前项目的排查结果为全部通过，将在点击确定后提交",
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        success: (result) => {
          if (result.confirm) {
            that.commitForm("pass")
          }
        },
      })
    } else {
      this.commitForm(unusualList)
    }
  }, 1000),

  commitForm: function (type) {
    console.log("type", type)
    let that = this
    dd.showLoading({
      content: '正在提交',
    })
    for (let i = 0; i < this.data.checkItemList[0].contentList.length; i++) {
      this.data.checkItemList[0].contentList[i].schoolId = app.globalData.departmentId
      this.data.checkItemList[0].contentList[i].createUserId = app.globalData.userId
      this.data.checkItemList[0].contentList[i].createUserName = app.globalData.realname
      this.data.checkItemList[0].contentList[i].address = this.data.checkAddress
      this.data.checkItemList[0].contentList[i].className = this.data.checkClass
      this.data.checkItemList[0].contentList[i].categoryName = this.data.categoryName
      this.data.checkItemList[0].contentList[i].item = this.data.checkItemList[0].item;
      this.data.checkItemList[0].contentList[i].connectTime = this.data.connectTime
      this.data.checkItemList[0].contentList[i].latitude = this.data.latitude ? this.data.latitude : "定位失败"
      this.data.checkItemList[0].contentList[i].longitude = this.data.longitude ? this.data.longitude : "定位失败"
      this.data.checkItemList[0].contentList[i]["schoolId"] = parseInt(app.globalData.departmentId)
    }
    // console.log(this.data.checkItemList[0].contentList)
    // return
    //如果要求已经插过不能再插，要修改接口。
    dd.httpRequest({
      url: app.baseUrl + '/DingDingSystem2/addInspectItemCondition',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: JSON.stringify(this.data.checkItemList[0].contentList),
      dataType: 'text',
      success: res => {
        //获取异常的inspectConditionId
        let inspectConditionId;
        if(res.data != null && res.data != ""){
          inspectConditionId = res.data.split(",")
        }
        //有异常上报安全隐患
        if ("pass" != type) {
          dd.showLoading({
            content: '推送异常信息',
          })
          let countFail = 0,
            bind = [],
            unbind = []
          // console.log(type)
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/getAccessTokenForSendMsg',
            method: 'GET',
            data: {
              schoolId: app.globalData.departmentId
            },
            dataType: 'json',
            success: res => {
              let access_token = res.data.access_token
              dd.httpRequest({
                url: app.baseUrl + '/DingDingSystem/getChargeManDingDingId',
                method: 'POST',
                headers:{
                  "Content-Type" : "application/json"
                },
                data: JSON.stringify({
                  categoryId: this.data.checkItemList[0].pushCategoryId,
                  schoolId: app.globalData.departmentId
                }),
                dataType: 'json',
                success: res => {
                  let chargeManNumber = res.data.length
                  // if (res.data) {
                  for (let i = 0; i < res.data.length; i++) {
                    if (res.data[i].res == "fail") {
                      unbind.push(res.data[i].msg)
                    } else {
                      bind.push(res.data[i].msg)
                    }
                  }
                  console.log("type", type)
                  for (let i = 0; i < type.length; i++) {
                    dd.httpRequest({
                      url: app.baseUrl + '/DingDingSystem/safetyReport',
                      method: 'POST',
                      headers:{
                        "Content-Type" : "application/json"
                      },
                      data: JSON.stringify({
                        schoolId: parseInt(app.globalData.departmentId),
                        safetyLevel: 2,
                        address: this.data.checkAddress,
                        content: type[i].recordContent,
                        photo: type[i].imageUrl.join(","),
                        video :  type[i].video,
                        reporter: app.globalData.userId,
                        categoryId: this.data.checkItemList[0].pushCategoryId,
                        inspectConditionId: inspectConditionId[i],
                        itemContent: type[i].content
                      }),
                      dataType: 'json',
                      success: res => {
                        if ('success' == res.data.res) {

                          if (chargeManNumber) {
                            for (let i = 0; i < bind.length; i++) {
                              console.log(reqData, bind[i])
                              let datetime = util.formatTime(new Date())
                              dd.httpRequest({
                                url: app.baseUrl + '/DingDingSystem/sendMessage',
                                method: 'POST',
                                headers:{
                                  "Content-Type" : "application/json"
                                },
                                data: JSON.stringify({
                                  schoolId: app.globalData.departmentId,
                                  template: 1,
                                  accessToken: access_token,
                                  touser: bind[i],
                                  safetySceneId: res.data.data,
                                  data: {
                                    first: {
                                      value: "【巡检异常】"
                                    },
                                    keyword1: {
                                      value: app.globalData.realname
                                    },
                                    keyword2: {
                                      value: datetime
                                    },
                                    keyword3: {
                                      value: `巡检时在${this.data.checkAddress}发现异常，请及时查看!`
                                    }
                                  }
                                }),
                                dataType: 'json'
                              })
                            }
                          }
                          
                        } else {
                          countFail++
                        }
                        dd.hideLoading()
                      },
                      fail: () => {
                        console.log("有异常1")
                        dd.showToast({
                          content: '网络异常！',
                          type: "fail"
                        })
                      }
                    })
                  }
                  // }
                },
                fail: () => {
                  console.log("有异常2")
                  dd.showToast({
                    content: '网络异常！',
                    type: "fail"
                  })
                },
                complete: () => {
                  if (countFail != 0) {
                    dd.showToast({
                      content: `有${countFail}个异常上报失败！`,
                      mask: true,
                      icon: "none"
                    })
                  }
                  // console.log(unbind)
                  if (unbind.length != 0) {
                    let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                    dd.confirm({
                      title: "提示",
                      content: msg,
                      success(result) {
                        if (result.confirm) {
                          let pages = getCurrentPages(); //当前页面
                          let prevPage = pages[pages.length - 2]; //上一页面
                          prevPage.setData({ //直接给上移页面赋值
                            submitRefresh: 1
                          });
                          // 提示框隐藏后 跳转
                          dd.navigateBack({
                            delta: 1
                          })
                        }
                      }
                    })
                  } else {
                    setTimeout(function () {
                      let pages = getCurrentPages(); //当前页面
                      let prevPage = pages[pages.length - 2]; //上一页面
                      prevPage.setData({ //直接给上移页面赋值
                        submitRefresh: 1
                      });
                      // 提示框隐藏后 跳转
                      dd.navigateBack({
                        delta: 1
                      })
                    }, 1000)
                  }

                }
              })
            },
            fail: () => {
              console.log("有异常3")
              dd.hideLoading()
              dd.showToast({
                content: '网络异常！',
                type:"fail"
              })
            }
          })

        } else {
          //全部排查内容正常执行的操作
          dd.hideLoading();
          dd.showToast({
            content: '提交成功！',
            type: "success"
          })
          setTimeout(function () {
            let pages = getCurrentPages(); //当前页面
            let prevPage = pages[pages.length - 2]; //上一页面
            prevPage.setData({ //直接给上移页面赋值
              submitRefresh: 1
            });
            // 提示框隐藏后 跳转
            dd.navigateBack({
              delta: 1
            })
          }, 1000)
        }


      },
      fail(res) {
        console.log("有异常4")
        dd.showToast({
          content: '网络异常！',
          mask: true,
          type: "fail"
        })
      }
      
    })
  },

  //新增视频录制功能
  press:function (e) {

    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    let checkItemList = this.data.checkItemList
    dd.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 10,
      success: res => {
        console.log("res", res)
        
        if(res.size > 2097152){
          dd.showToast({
            content: '文件大于2M！',
            type: 'fail'
            // image: "/images/error.png"
          })
        }else{
          dd.showLoading({
            content: '视频上传中...',
          })
          dd.uploadFile({
            url: app.baseUrl + '/DingDingSystem/fileUpload2',
            filePath: res.filePath,
            fileName: 'file',
            fileType: 'video',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success:res=>{
              checkItemList[itemIndex].contentList[detailIndex].video = res.data
              checkItemList[itemIndex].contentList[detailIndex].videoSrc = app.imageUrl + res.data
              this.setData({
                checkItemList: checkItemList
              })
              dd.hideLoading()
            }
          })
        }
      },
      fail(res){
        console.log("-------调用失败")
      }
    })
  },
  delelteVideo:function(e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[0])
    let detailIndex = parseInt(e.currentTarget.id.split('-')[1])
    let checkItemList = this.data.checkItemList
    let target = checkItemList[itemIndex].contentList[detailIndex].video
    dd.showActionSheet({
      items: ['删除视频'],
      success: res => {
        console.log("res", res)
        if (res.index != -1) {
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/deleteVideo',
            method: 'POST',
            headers:{
              "Content-Type" : "application/json"
            },
            data: JSON.stringify({
              filename: target.split("video/")[1]
            }),
            dataType: 'text',
            success: res => {
              if(res.data == "success"){
                checkItemList[itemIndex].contentList[detailIndex].video = ""
                this.setData({
                  checkItemList : checkItemList
                })
              }
            }
          })
        }
      }
    })
  }

});